package com.gyh.system.scheduler.utils;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;

import com.gyh.system.common.exception.RException;
import com.gyh.system.common.utils.Constant.ScheduleStatus;
import com.gyh.system.scheduler.entity.ScheduleJob;

/**
* @author 作者 gyh:
* @version 创建时间：2018年1月6日 上午1:28:31
* 
*/
public class ScheduleUtils {
	
	private static final String JOB_NAME = "Task_";
	
	
	/**
	 * 获取triggerKey
	 * @param id
	 * @return
	 */
	public static TriggerKey getTriggerKey(Long id) {
		return TriggerKey.triggerKey(JOB_NAME+id);
	}

	/**
	 * 获取JobKey
	 * @param id
	 * @return
	 */
	public static JobKey getJobKey(Long id) {
		return JobKey.jobKey(JOB_NAME+id);
	}
	
	/**
	 * 获取触发器
	 * @param sched
	 * @param id
	 * @return
	 */
	public static CronTrigger getCronTrigger(Scheduler sched , Long id) {
		try {
			return (CronTrigger) sched.getTrigger(getTriggerKey(id));
		} catch (SchedulerException e) {
			throw new RException("获取触发器失败", e);
		}
	}
	
	
	/**
	 * 创建定时任务
	 * @param scheduler
	 * @param schedulerJob
	 */
	public static void createSchedulerJob(Scheduler scheduler,ScheduleJob scheduleJob) {
		try {
			//构建job信息
			JobDetail jobDetail = JobBuilder.newJob(ScheduleJobExecuter.class).withIdentity(getJobKey(scheduleJob.getId())).build();
			
			//创建 Cron 表达式调度器
			CronScheduleBuilder schedBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression())
					.withMisfireHandlingInstructionDoNothing();
			//根据 Cron 表达式调度器构建一个新的触发器
			CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(scheduleJob.getId())).withSchedule(schedBuilder).build();		
			
			//在job中添加参数数据
			jobDetail.getJobDataMap().put(ScheduleJob.JOB_PARAM_KEY, scheduleJob.toJson());
			
			//在shcedule中注册Job和trigger
			scheduler.scheduleJob(jobDetail, trigger);
			
			 //暂停任务
            if(scheduleJob.getStatus() == ScheduleStatus.PAUSE.getValue()){
            	pauseJob(scheduler, scheduleJob.getId());
            }
		
		} catch (SchedulerException e) {
			throw new RException("任务创建失败 ",e);
		}
	}
	
	/**
     * 更新定时任务
     */
    public static void updateScheduleJob(Scheduler scheduler, ScheduleJob scheduleJob) {
        try {
        	
            TriggerKey triggerKey = getTriggerKey(scheduleJob.getId());

            //表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression())
            		.withMisfireHandlingInstructionDoNothing();

            CronTrigger trigger = getCronTrigger(scheduler, scheduleJob.getId());
            
            //按新的cronExpression表达式重新构建trigger
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
            
            //参数
            trigger.getJobDataMap().put(ScheduleJob.JOB_PARAM_KEY, scheduleJob.toJson());
            
            scheduler.rescheduleJob(triggerKey, trigger);
            
            //暂停任务
            if(scheduleJob.getStatus() == ScheduleStatus.PAUSE.getValue()){
            	pauseJob(scheduler, scheduleJob.getId());
            }
            
        } catch (SchedulerException e) {
            throw new RException("更新定时任务失败", e);
        }
    }
	
	/**
     * 暂停任务
     */
    public static void pauseJob(Scheduler scheduler, Long id) {
        try {
            scheduler.pauseJob(getJobKey(id));
        } catch (SchedulerException e) {
            throw new RException("暂停定时任务失败", e);
        }
    }
    
    /**
     * 恢复任务
     */
    public static void resumeJob(Scheduler scheduler, Long id) {
        try {
            scheduler.resumeJob(getJobKey(id));
        } catch (SchedulerException e) {
            throw new RException("恢复定时任务失败", e);
        }
    }
    
    /**
     * 删除定时任务
     */
    public static void deleteScheduleJob(Scheduler scheduler, Long id) {
        try {
            scheduler.deleteJob(getJobKey(id));
        } catch (SchedulerException e) {
            throw new RException("删除定时任务失败", e);
        }
    }
	
}
